// 116.填充每个节点的下一个右侧节点指针
package Leetcode_Second_Brush;

import java.util.Deque;
import java.util.LinkedList;

class Node {
    public int val;
    public Node left;
    public Node right;
    public Node next;

    public Node() {
    }

    public Node(int _val) {
        val = _val;
    }

    public Node(int _val, Node _left, Node _right, Node _next) {
        val = _val;
        left = _left;
        right = _right;
        next = _next;
    }
};

public class Solution116 {
    public Node connect(Node root) {
        if (root == null)
            return null;

        Deque<Node> queue = new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()) {
            int size = queue.size();
            // 保存每一层的前面一个节点，用于调整next指针
            Node prev = null;
            for (int i = 0; i < size; i++) {
                Node curr = queue.poll();
                if (prev != null)
                    prev.next = curr;
                prev = curr;
                // 如果next指针不赋值，则为null
                if (curr.left != null)
                    queue.offer(curr.left);
                if (curr.right != null)
                    queue.offer(curr.right);
            }
        }

        return root;
    }
}